import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";

interface homeState {
  loading: boolean;
  error: boolean;
  list: {
    uid: number;
    id: string;
    url: string;
    title: string;
    desc: string;
    greter: number;
		zan: boolean
  }[];
  title: {
    id: number;
    name: string;
  }[];
}

export const fetchTitle = createAsyncThunk("home/fetchTitle", async () => {
  const resp = await axios.get("/api/home/title");
  return resp.data;
});

interface Params {
  id?: number;
  pageCode?: number;
  pageSize?: number;
}

export const fetchContent = createAsyncThunk(
  "home/fetchContent",
  async (params?: Params) => {
    const resp = await axios.get("/api/home/content", { params });
    return resp.data;
  }
);

const initialState: homeState = {
  loading: true,
  error: false,
  list: [],
  title: [],
};

const homeSlice = createSlice({
  name: "home",
  initialState,
  reducers: {
    clearList(state) {
      state.list = [];
			state.error = false;
    },
  },
  extraReducers: {
    [fetchTitle.pending.type](state) {
      state.loading = true;
    },
    [fetchTitle.fulfilled.type](state, action) {
      state.loading = false;
      state.title = action.payload.data;
    },
    [fetchContent.pending.type](state) {
      state.loading = true;
    },
    [fetchContent.fulfilled.type](state, action) {
      state.loading = false;
      state.list = state.list.concat(action.payload.data);
    },
    [fetchContent.rejected.type](state, action) {
      state.loading = false;
      state.error = true;
    },
  },
});

export const { clearList } = homeSlice.actions;
export default homeSlice;
